<template>
  <el-card class="box-card">
    <template #header>
      <div class="header-container">
        <div class="page-title-container">
          <h2 class="page-title">
            <el-icon class="title-icon">
              <User />
            </el-icon>
            <span>用户信息管理</span>
          </h2>
        </div>
        <div class="search-actions-container">
          <div class="search-group">
            <el-button class="button" type="primary" @click="openDialog()">
              新增用户
            </el-button>
            <el-button class="button" type="danger" @click="batchDelete" :disabled="!multipleSelection.length">
              批量删除
            </el-button>
          </div>
        </div>
      </div>
    </template>

    <el-table :data="users" style="width: 100%" @selection-change="handleSelectionChange" border stripe
      v-loading="loading">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="user_id" label="用户编号" width="80" align="center" />
      <el-table-column prop="real_name" label="姓名" width="100" align="center" />
      <el-table-column prop="username" label="用户名" width="120" align="center" />
      <el-table-column prop="email" label="邮箱" align="center" />
      <el-table-column prop="phone" label="电话" width="120" align="center" />
      <el-table-column prop="create_time" label="注册时间" width="150" align="center" />
      <el-table-column prop="last_login" label="最后登录" width="150" align="center" />
      <el-table-column label="操作" width="240" align="center" fixed="right">
        <template #default="scope">
          <el-button class="action-btn details-button" type="warning" size="small" plain @click="openDialog(scope.row)">
            详情
          </el-button>

          <el-tooltip content="查看用户画像" placement="top">
            <el-button class="action-btn profile-button-highlight" size="small" plain
              @click="viewUserProfile(scope.row)">
              用户画像
            </el-button>
          </el-tooltip>

          <el-button class="action-btn delete-button" type="danger" size="small" plain @click="deleteUser(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
      <el-pagination v-model:currentPage="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
        :background="true" layout="total, sizes, prev, pager, next, jumper" :total="totalCount"
        @size-change="handleSizeChange" @current-change="handlePageChange" />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="ID">
          <el-input v-model="form.user_id" disabled />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="form.real_name" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" v-if="!form.user_id">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.gender" placeholder="请选择">
            <el-option label="未知" :value="0" />
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker v-model="form.birth_date" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="禁用" :value="0" />
            <el-option label="正常" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="头像 URL">
          <el-input v-model="form.avatar" />
        </el-form-item>
        <el-form-item label="注册时间">
          <el-input v-model="form.create_time" disabled />
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input v-model="form.update_time" disabled />
        </el-form-item>
        <el-form-item label="最后登录">
          <el-input v-model="form.last_login" disabled />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import axios from 'axios'
import { User } from '@element-plus/icons-vue'

export default {
  components: {
    User
  },
  data() {
    return {
      users: [],
      multipleSelection: [],
      dialogVisible: false,
      dialogTitle: '',
      loading: false,
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      form: {
        user_id: null,
        username: '',
        real_name: '',
        email: '',
        phone: '',
        password: '',
        gender: 0,
        birth_date: null,
        status: 1,
        avatar: '',
        create_time: '',
        update_time: '',
        last_login: ''
      }
    }
  },
  methods: {
    fetchUsers() {
      this.loading = true;
      const params = {
        page: this.currentPage,
        size: this.pageSize
      };

      axios.get('http://localhost:8080/user/allpage', { params })
        .then(res => {
          // 适配 PageInfo 结构
          const pageData = res.data;
          this.users = (pageData.list || []).map(u => ({
            user_id: u.userId,
            username: u.username,
            real_name: u.realName,
            email: u.email,
            phone: u.phone,
            create_time: u.registerTime?.replace('T', ' ').slice(0, 16),
            last_login: u.lastLogin?.replace('T', ' ').slice(0, 16),
            password: u.password,
            gender: u.gender,
            birth_date: u.birthDate,
            status: u.status,
            avatar: u.avatar,
            update_time: u.updateTime?.replace('T', ' ').slice(0, 16) || ''
          }));
          this.totalCount = pageData.total || 0;
        })
        .catch(err => {
          console.error('获取用户列表失败', err);
          this.$message.error("获取用户列表失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    openDialog(row = null) {
      if (row) {
        this.dialogTitle = '编辑用户信息'
        this.form = { ...row }
      } else {
        this.dialogTitle = '新增用户'
        this.form = {
          user_id: null,
          username: '',
          real_name: '',
          email: '',
          phone: '',
          password: '',
          gender: 0,
          birth_date: null,
          status: 1,
          avatar: '',
          create_time: '',
          update_time: '',
          last_login: ''
        }
      }
      this.dialogVisible = true
    },
    submitForm() {
      let payload = {
        userId: this.form.user_id,
        username: this.form.username,
        realName: this.form.real_name,
        email: this.form.email,
        phone: this.form.phone,
        password: this.form.password,
        gender: this.form.gender,
        birthDate: this.form.birth_date,
        status: this.form.status,
        avatar: this.form.avatar
      }
      if (this.form.user_id) {
        axios.post('http://localhost:8080/user/user_update', payload)
          .then(() => {
            this.dialogVisible = false
            this.fetchUsers()
            this.$message.success("用户信息更新成功");
          })
          .catch(err => {
            console.error('更新用户失败', err);
            this.$message.error("更新用户失败");
          })
      } else {
        axios.post('http://localhost:8080/user/user_add', payload)
          .then(() => {
            this.dialogVisible = false
            this.fetchUsers()
            this.$message.success("用户添加成功");
          })
          .catch(err => {
            console.error('新增用户失败', err);
            this.$message.error("新增用户失败");
          })
      }
    },
    deleteUser(user) {
      this.$confirm('确认删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return axios.delete(`http://localhost:8080/user/userdelete/${user.user_id}`);
      }).then(() => {
        this.$message.success("用户删除成功");
        this.fetchUsers();
      }).catch(error => {
        if (error !== 'cancel' && error !== 'close') {
          console.error('删除用户失败:', error);
          this.$message.error("删除用户失败");
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    batchDelete() {
      const ids = this.multipleSelection.map(item => item.user_id);
      this.$confirm(`确认删除选中的${ids.length}个用户吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return Promise.all(ids.map(id => axios.delete(`http://localhost:8080/user/userdelete/${id}`)));
      }).then(() => {
        this.$message.success(`成功删除${ids.length}个用户`);
        this.fetchUsers();
        this.multipleSelection = [];
      }).catch(error => {
        if (error !== 'cancel' && error !== 'close') {
          console.error('批量删除失败:', error);
          this.$message.error("批量删除失败");
        }
      });
    },
    viewUserProfile(user) {
      this.$router.push({
        name: 'admin-user-profile',
        params: { userId: user.user_id }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchUsers();
    },
    handlePageChange(val) {
      this.currentPage = val;
      this.fetchUsers();
    }
  },
  mounted() {
    this.fetchUsers()
  }
}
</script>

<style scoped>
/* 卡片整体优化 */
.box-card {
  margin: 20px;
  border-radius: 16px;
  transition: box-shadow 0.3s ease;
  background: #ffffff;
}

.el-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

/* 页头结构 */
.header-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.page-title-container {
  margin-bottom: 0;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 22px;
  color: #303133;
  margin: 0;
  font-weight: bold;
}

.title-icon {
  margin-right: 10px;
  font-size: 24px;
  color: #409EFF;
  transition: transform 0.3s ease;
}

.page-title:hover .title-icon {
  transform: rotate(10deg);
}

/* 搜索按钮区域 */
.search-actions-container {
  display: flex;
  justify-content: flex-end;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.button {
  margin-left: 10px;
  transition: all 0.3s ease;
  border-radius: 20px;
  font-weight: 500;
}

.button:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 10px rgba(64, 158, 255, 0.3);
}

/* 操作按钮样式 */
.text-button {
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  cursor: pointer;
  transition: color 0.2s ease;
  font-weight: 500;
}

.details-button {
  color: rgb(223, 179, 59);
}

.details-button:hover {
  color: orange;
}

.profile-button {
  color: #409EFF;
}

.profile-button:hover {
  color: #66b1ff;
}

.delete-button {
  color: rgb(212, 80, 80);
}

.delete-button:hover {
  color: #f56c6c;
  font-weight: bold;
}

.text-button:not(:last-child) {
  margin-right: 1em;
}

/* 表格高亮 */
.el-table__row:hover {
  background-color: #f5f7fa !important;
}

/* 分页器居中 */
.demo-pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表单输入优化 */
.el-input {
  transition: border 0.3s ease;
}

.el-input:hover {
  border-color: #409EFF;
}

/* 对话框动效 */
.el-dialog {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
    transform: scale(0.95);
  }

  100% {
    opacity: 1;
    transform: scale(1);
  }
}

/* 头像预览优化 */
.avatar-preview {
  margin-top: 10px;
  text-align: center;
}

.avatar-preview img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 1px solid #ccc;
  object-fit: cover;
}

/* 通用按钮动效 */
.action-btn {
  border-radius: 16px;
  transition: all 0.2s ease-in-out;
  font-weight: 500;
  padding: 5px 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 鼠标悬浮放大一点 + 加深颜色 */
.action-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 点击轻微缩小模拟按下效果 */
.action-btn:active {
  transform: scale(0.97);
  box-shadow: none;
}

/* 特定按钮颜色再加强一点点对比 */
.details-button {
  background-color: #fdf6ec;
  color: #e6a23c;
  border-color: #f3d19e;
}

.details-button:hover {
  background-color: #faecd8;
}

.profile-button {
  background-color: #ecf5ff;
  color: #409EFF;
  border-color: #b3d8ff;
}

.profile-button:hover {
  background-color: #d1ecff;
}

.delete-button {
  background-color: #fef0f0;
  color: #f56c6c;
  border-color: #fab6b6;
}

.delete-button:hover {
  background-color: #fde2e2;
}

/* 粉色震撼特效的用户画像按钮 */
.profile-button-highlight {
  position: relative;
  background: linear-gradient(135deg, #fda3c4, #f962a3, #d63d7c);
  color: #fff;
  border: none;
  border-radius: 20px;
  font-weight: bold;
  overflow: hidden;
  z-index: 1;
  animation: pulse-pink 2.2s infinite;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  box-shadow: 0 0 12px rgba(249, 98, 163, 0.6);
}

.profile-button-highlight:hover {
  transform: scale(1.08);
  box-shadow: 0 0 18px rgba(249, 98, 163, 0.9);
}

.profile-button-highlight:active {
  transform: scale(0.96);
}

/* 粉色呼吸动画 */
@keyframes pulse-pink {
  0% {
    box-shadow: 0 0 10px rgba(249, 98, 163, 0.5);
  }

  50% {
    box-shadow: 0 0 24px rgba(249, 98, 163, 0.85);
  }

  100% {
    box-shadow: 0 0 10px rgba(249, 98, 163, 0.5);
  }
}
</style>